//引入所需模块
let http = require('http');
let fs = require('fs');
let url = require('url');

//创建http服务器
http.createServer(function (req, res) {
    //获取访问地址
    let sm = req.url;
    console.log(sm);
    if (sm === '/') {
        fs.readFile('./html/login.html', function (err, data) {
            res.setHeader('Content-Type', 'text/html;charset=utf-8');
            if (!err) {
                res.end(data.toString());
            } else {
                fs.readFile('./html/404.html', function (e, d) {
                    res.end(d.toString());
                })
            }
        })
    } else if(sm === '/login.html'){
        fs.readFile('./html/login.html', function (err, data) {
            res.setHeader('Content-Type', 'text/html;charset=utf-8');
            if (!err) {
                res.end(data.toString());
            } else {
                fs.readFile('./html/404.html', function (e, d) {
                res.end(d.toString())
                })
            }
        })
    }else if(sm === '/chat.html'){
        fs.readFile('./html/chat.html', function (err, data) {
            res.setHeader('Content-Type', 'text/html;charset=utf-8');
            if (!err) {
                res.write(data.toString());
                res.end();
            } else {
                fs.readFile('./html/404.html', function (e, d){
                    res.write(d.toString());
                    res.end();
                })
            }
        })
    }else if(sm.indexOf('js')!==-1){
       fs.readFile("." + sm,function (e,d) {
           if (!e){
               res.setHeader("Content-type", "text/javascript;charset=utf-8;");
               res.write(d.toString());
               res.end();
           }else {
               res.setHeader('Content-Type', 'text/html;charset=utf-8');
               res.end('404');
           }
       })
    }else if(sm.indexOf('css')!==-1){
        fs.readFile("." + sm,function (e,d) {
            if (!e){
                res.setHeader("Content-type", "text/css;charset=utf-8;");
                res.write(d.toString());
                res.end();
            }else {
                res.setHeader('Content-Type', 'text/html;charset=utf-8');
                res.end('404');
            }
        })
    }
}).listen(8080,() => {
    console.log('Server running at http://127.0.0.1:8080')
});


